import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/bean/bean_video_course.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/train/train_course_item_widget.dart';
import 'package:flutter_learn_vi/src/page/train/train_degree_of_statisfaction_page.dart';
import 'package:flutter_learn_vi/src/page/train/train_tab_details2_student_page.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_course_item_widget2.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_page.dart';
import 'package:flutter_learn_vi/src/page/train/train_user_check_recoder_page.dart';
import 'package:flutter_learn_vi/src/utils/color_utils.dart';
import 'package:flutter_learn_vi/src/utils/string_utils.dart';
import 'package:get/get.dart';

import '../common/location_page.dart';
import 'controller/train_details_controller.dart';
import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/14.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///

///培训详情
class TrainDetailsPage extends StatefulWidget {
  //培训ID
  final TrainApproveBean approveBean;
  final TrainBean userSelectTrainBena;
  final bool isScaffold;
  final TrainBean trainBean;

  const TrainDetailsPage(
      {Key key,
      @required this.approveBean,
      this.trainBean,
      this.isScaffold = true,
      this.userSelectTrainBena})
      : super(key: key);

  @override
  _TrainDetailsPageState createState() => _TrainDetailsPageState();
}

class _TrainDetailsPageState extends State<TrainDetailsPage> with TrainModel {
  @override
  void initState() {
    super.initState();
    if (widget.trainBean != null) {
      _trainBean = widget.trainBean;
      _isLoading = false;
    } else {
      getMyTrainDetailsFunction();
    }
    Future.delayed(Duration.zero, () {
      startTimer();
    });
  }

  Timer _timer;

  startTimer() {
    _timer = Timer.periodic(Duration(seconds: 10), (timer) {
      getMyTrainDetailsFunction();
    });
  }

  stopTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    stopTimer();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isScaffold) {
      return Scaffold(
        appBar: AppBar(
          title: Text("培训详情"),
        ),

        ///填充布局
        body: Container(
            width: double.infinity,
            height: double.infinity,
            child: buildBodyWidget()),
      );
    } else {
      return buildBodyWidget();
    }
  }

  Widget buildBodyWidget() {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_trainBean == null) {
      return NoDataWidget(
        clickCallBack: () {
          getMyTrainDetailsFunction();
        },
      );
    }
    return SingleChildScrollView(
      child: Container(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            HomeLocationWidget(pageTag: widget.approveBean.trainId.toString()),
            buildTrainBase(),
            SizedBox(
              height: 0,
            ),
            buildCourseAndTeacher(),
          ],
        ),
      ),
    );
  }

  Widget buildTrainBase() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 4),
      child: Card(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  buildLeftTitle("培训名称"),
                  Expanded(
                    child: Text(
                      "${_trainBean.trainName}",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Row(
                children: [
                  buildLeftTitle("培训时间"),
                  SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: Text(
                      "${_trainBean.startStudyTime} ~ ${_trainBean.endStudyTime}",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  buildLeftTitle("培训简介"),
                  SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: GestureDetector(
                      onLongPress: () {
                        if (_trainBean.trainRemark != null &&
                            _trainBean.trainRemark.length > 50) {
                          Get.defaultDialog(
                            radius: 4,
                            title: "培训简介",
                            content: Container(
                              constraints: BoxConstraints(maxHeight: 600),
                              child: SingleChildScrollView(
                                child: Text(_trainBean.trainRemark),
                              ),
                            ),
                            confirm: Container(
                              alignment: Alignment.center,
                              child: TextButton(
                                onPressed: () {
                                  Get.back(result: true);
                                },
                                child: Text(
                                  "确认",
                                  style: TextStyle(color: Colors.blue),
                                ),
                              ),
                              width: 100,
                            ),
                          );
                        }
                      },
                      child: Text(
                        "${_trainBean.trainRemark ?? "--"}",
                        maxLines: 4,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(height: 8),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  buildLeftTitle("参与部门"),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: 2),
                      child: Wrap(
                        runSpacing: 10,
                        children: buildDepartment(),
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              (!widget.isScaffold && widget.approveBean.commitTime != null)
                  ? Row(
                      children: [
                        buildLeftTitle("申请时间"),
                        Expanded(
                          child: Text("${widget.approveBean.commitTime}"),
                        )
                      ],
                    )
                  : Container(),
              SizedBox(
                height: 8,
              ),
              widget.approveBean.approeTime != null
                  ? Row(
                      children: [
                        buildLeftTitle(widget.isScaffold ? "创建时间" : "审批时间"),
                        Expanded(
                          child: Text("${widget.approveBean.approeTime}"),
                        )
                      ],
                    )
                  : Container(),
              Container(
                child: buildControllerButton(),
              ),
              Container(
                child: buildUserControllerButton(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildLeftTitle(String title) {
    return Container(
      constraints: BoxConstraints(minWidth: 68),
      child: Text("$title"),
    );
  }

  ///参与的部门
  List<Widget> buildDepartment() {
    String department = _trainBean.selectDepartment;
    if (StringUtils.isEmpty(department)) {
      return [buildDepartMentCell("全部部门")];
    } else {
      if (department.contains(",")) {
        List<String> list = department.split(",");
        List<Widget> widgetList = [];
        list.forEach((element) {
          widgetList.add(buildDepartMentCell(element));
        });
        return widgetList;
      } else {
        return [buildDepartMentCell("$department")];
      }
    }
  }

  ///教师与课程
  Widget buildCourseAndTeacher() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 4),
      child: Card(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Container(
                    width: 4,
                    height: 14,
                    margin: EdgeInsets.only(right: 8),
                    color: Colors.blueAccent,
                  ),
                  Expanded(
                    child: Text(
                      "培训内容",
                      style: TextStyle(
                        fontSize: 14,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              buildTipsWidget(),
              GetBuilder(
                init: TrainDetailsController(),
                builder: (TrainDetailsController controller) {
                  return buildListView();
                },
              ),
              SizedBox(
                height: 10,
              ),
            ],
          ),
        ),
      ),
    );
  }

  buildTipsWidget() {
    if (_trainBean == null) {
      return SizedBox();
    }
    String trainLine = _trainBean.trainLine;
    if (trainLine == "offline") {
      // trainLineStr = "线下";
      return Text(
        "* 请注意：在培训时间范围内才可加入学习，加入学习后，观看在线学习内容才会记入培训档案中，如未加入学习，将不会将观看在线课\n\n* 请注意：教师开课后方可点击签到进行培训打卡\n",
        style: TextStyle(
          fontSize: 14,
          color: Colors.red,
        ),
      );
    } else {
      //trainLineStr = "线上课程学习";
      return Text(
        "* 请注意：在培训时间范围内才可加入学习，加入学习后，观看在线学习内容才会记入培训档案中，如未加入学习，将不会将观看在线课\n\n* 请注意：参与学习后，请点击下方课程列表参与学习\n",
        style: TextStyle(
          fontSize: 14,
          color: Colors.red,
        ),
      );
    }
  }

  ListView buildListView() {
    int count = 0;
    if (_trainBean.courseList != null) {
      count = _trainBean.courseList.length;
    }
    if (_trainBean.videoCourseEntityList != null) {
      count = count + _trainBean.videoCourseEntityList.length;
    }

    return ListView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        CourseAndTeacherBean cubean;
        BeanVideoCourse beanVideoCourse;
        if (_trainBean.courseList.length > 0 &&
            index < _trainBean.courseList.length) {
          cubean = _trainBean.courseList[index];
          return TrainTeacherCourseItemWidget2(
            cubean: cubean,
            index: index,
          );
        } else {
          beanVideoCourse = _trainBean
              .videoCourseEntityList[index - _trainBean.courseList.length];
          return TrainCourseVideoItemWidget(
            videoCourse: beanVideoCourse,
            index: index,
            trainId: _trainBean.trainId,
          );
        }
      },
    );
  }

  Widget buildDepartMentCell(String title) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          margin: EdgeInsets.only(right: 10),
          padding: EdgeInsets.only(left: 6, right: 6, top: 1, bottom: 2),
          decoration: BoxDecoration(
              color: ColorUtils.getRandomColor(),
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Text(
            "$title",
            style: TextStyle(color: Colors.white, fontSize: 9),
          ),
        )
      ],
    );
  }

  bool _isLoading = true;
  TrainBean _trainBean;

  Future<bool> getMyTrainDetailsFunction() async {
    _trainBean = await getTrainNetDatils(trainId: widget.approveBean.trainId);
    _isLoading = false;
    if (mounted) {
      setState(() {});
    }
    return Future.value(true);
  }

  buildUserControllerButton() {
    if (_trainBean == null) {
      return SizedBox();
    }

    if (widget.userSelectTrainBena == null) {
      return SizedBox();
    }
    int showCheckResult = _trainBean.showCheckResult;
    int showTeacherDegree = _trainBean.showTeacherDegree;
    int showTrainDegree = _trainBean.showTrainDegree;
    return Wrap(
      crossAxisAlignment: WrapCrossAlignment.start,
      children: [
        showTeacherDegree == 0
            ? SizedBox()
            : ElevatedButton(
                onPressed: () async {
                  await Get.to(() => TrainTeacherPage(
                        trainId: widget.approveBean.trainId,
                      ));
                },
                child: Text("培训教师满意度测评"),
              ),
        SizedBox(
          width: 20,
        ),
        showTrainDegree == 0
            ? SizedBox()
            : ElevatedButton(
                onPressed: () async {
                  await Get.to(() => TrainDegreeOfStatisFactionPage(
                        trainId: widget.approveBean.trainId,
                        tag: 'trainMain',
                      ));
                },
                child: Text("培训管理满意度测评"),
              ),
        SizedBox(
          width: 20,
        ),
        showCheckResult == 0
            ? SizedBox()
            : ElevatedButton(
                onPressed: () async {
                  await Get.to(() => TrainUserCheckRecoderPage(
                        trainId: widget.approveBean.trainId,
                        tag: 'trainMain',
                      ));
                },
                child: Text("查看考核情况"),
              ),
        SizedBox(
          width: 20,
        ),
      ],
    );
  }

  buildControllerButton() {
    if (_trainBean == null) {
      return SizedBox();
    }
    if (_trainBean.showTrainExam == 0) {
      return SizedBox();
    }
    if (widget.userSelectTrainBena == null) {
      return SizedBox();
    }
    return ElevatedButton(
      onPressed: () async {
        if (widget.approveBean.examId == null) {
          if (_trainBean != null) {
            widget.approveBean.examId = _trainBean.examId;
          }
        }
        await Get.to(() => TrainTabDetails2StudentPage(
              approveBean: widget.approveBean,
            ));
      },
      child: Text("查看考试"),
    );
  }
}
